import * as bcrypt from 'bcryptjs';
import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
import {
  AuthProvider,
  findOrCreateUser,
  isEmailFree,
} from '../../../services/uctoo/uctoo_user';
import { validateSignUp } from '../../../helpers/dataValidation';
import { defaultRouteHandler } from '../../../../interfaces';
import { connectUserHasGroup } from '../../../services/uctoo/user_has_group';
import { connectUserHasAccount } from '../../../services/uctoo/user_has_account';

import db from '../../../lib/db';

const handleSignup: defaultRouteHandler = async (req, res) => {
  try {
    log.info('handleSignuphandleSignup');
    const body = await req.json();
    log.info(body);
    const { name, username, email, password, repeat_password, verifyCode } = body;
    //查询config表是否开启了验证码配置
    const EnableVerifyCode = await db.config.findFirst({
      where: {
        key: 'EnableVerifyCode',
      },
    }); 
    let account_id = null;   

    if(EnableVerifyCode.value === '1'){
      if (!verifyCode) {
        return res.status(400).json({ err: "42001", desc: "verify code is required" });
      }else{
        const nowTimestamp = Date.now();
        const date = new Date(nowTimestamp);
        const withTimezone = date.toISOString();
        //10分钟之内的验证码
        const tenMinutesAgo = new Date(nowTimestamp - 10 * 60 * 1000).toISOString();
        //sms_log表查询created_at时间十分钟之内的验证码是否存在
        const verifyCodeRecord = await db.sms_log.findFirst({
          where: {
            created_at: {
              gte: tenMinutesAgo,
            },
            code: verifyCode,
            event: 'verify',
          }}
        )
        //如果验证码存在，删除验证码记录
        if (verifyCodeRecord) {
          account_id = verifyCodeRecord.creator; //验证码注册的用户wechatopen_users表中的帐号
          await db.sms_log.delete({
            where: {
              id: verifyCodeRecord.id,
            },
          }); 
        }
                //如果验证码不存在，返回错误信息
        if (!verifyCodeRecord) {
          return res.status(400).json({ err: "42002", desc: "verify code is invalid" });
        }
      }
    }

    if(account_id){  //如果已有用户与帐号关联，则不生成新的uctoo_user，即一个微信公众号用户只能注册一个用户
      //user_has_account表查询是否存在用户
      const uctooUser = await db.user_has_account.findFirst({
        where: {
          account_id: account_id
        }}
      )
      if(uctooUser){
        return res.status(400).json({ err: "42003", desc: "user has registed with the same wechat account" });
      }
    }

    const lUser = {
      name,
      username,
      email,
      password,
      repeat_password,
    };
    
    if(email === null || email === undefined || email === ""){  //注册信息无email值，构造一个
      lUser.email = username + "@uctoo.com";
    }
    if(name === null || name === undefined || name === ""){  //注册信息无name值，构造一个
      lUser.name = username;
    }
    log.info(lUser);
    const isUserValidated = await validateSignUp(lUser);
    log.info('isUserValidated');
    log.info(isUserValidated);
    if (!isUserValidated) { 
      return res.status(400).json({ err: 'isUserValidated', desc: '注册信息验证错误，请检查用户名、邮箱格式，密码需包含大小写字母且8位以上' })
    };
    log.info('!UserValidated');
    log.info(!isUserValidated);
    const isEmailRegistered = await isEmailFree(lUser.email);
    log.info('isEmailRegistered');
    log.info(isEmailRegistered);
    if (!isEmailRegistered)
      return res.status(403).json({ err: 'isUserValidated', desc: '注册邮箱已存在' });

    await bcrypt.hash(password, 10).then((hash) => {
      lUser.password = hash;
    });
    log.info('lUser');
    log.info(lUser);
    const newUser = await findOrCreateUser(lUser, AuthProvider.Local);
    //新用户加入注册用户组
    const userGroupFromDb = await db.user_group.findFirst({
      where: {
        code: "login",
      },
    });
    const uctooUserHasGroup = {groupable_type:"uctoo_user", status : 1, creator:newUser.id, group_id:userGroupFromDb.id , groupable_id: newUser.id};
    const createdUserHasGroup = await connectUserHasGroup(uctooUserHasGroup);
    if (!createdUserHasGroup) { 
      return res.status(500).json({ err: 'createdUserHasGroup error', desc: '注册用户加入组错误' });
    }

    if(account_id){  //通过微信验证码注册的用户关联帐号
      //user_has_account表添加关联
      const uctooUserHasAccount = {account_type:"wechatopen_users", status : 1, creator:newUser.id, account_id:account_id , user_id: newUser.id};
      const createdUserHasAccount = await connectUserHasAccount(uctooUserHasAccount);
      if (!createdUserHasAccount) { 
        return res.status(500).json({ err: 'createdUserHasAccount error', desc: '注册用户关联帐号错误' });
      }
    }

    res.status(200).json({ code: "200", desc: "注册成功" });
  } catch (e) {
    log.error({ err: e.message, desc: e.response.data.error_description });
    res.status(500).json({ err: e.message, desc: e.response.data.error_description });
  }
};
export default handleSignup;
